var app = new Vue({
	el: '#app',
	data() {
		return {
      BASE_API: BASE_API,

			form: {
				cardID: '',
				name: '',
				gender: '',
				time: [],
        is_collect: '',
			},

      // 视屏列表
      videoList: [],

			table: {
				loading: false,
        head: [
          {label: 'ID', key: 'cardID', minWidth: '15%'},
          {label: '姓名', key: 'name', minWidth: '15%'},
          {label: '性别', key: 'gender_text', minWidth: '15%'},
          {label: '单位名称', key: 'department', minWidth: '20%'},
        ],
        data: []
      },
      selectedRows: [], // 选中行

      paging: {
        current: 1,
        pageSize: 10,
        total: 0,
      },

      // 就诊历史弹窗
      historyDialog: {
      	visible: false,
      	title: '',
      	tableData: []
      },

      // 新增弹窗
      addPatientDialog: {
      	visible: false,
      	showIdTip: false,
      	form: {
          id: '',
      		cardID: '',
      		name: '',
      		gender: '',
      		birthday: '',
          year: '',
          month: '',
          department: '',
          military: '',
      	},
      	rules: {
      		cardID: [
      			{ required: true, message: '请输入ID', trigger: 'blur' },
      		],
      		name: [
      			{ required: true, message: '请输入姓名', trigger: 'blur' },
      		],
      		gender: [
      			{ required: true, message: '请选择性别', trigger: 'blur' },
      		],
          birthday: [
            { required: true, trigger: 'change', validator: (rule, value, callback) => {
              if(!app.addPatientDialog.form.year) {
                callback(new Error('请输入出生年月'));
              } else if(!app.addPatientDialog.form.month) {
                callback(new Error('请输入出生年月'));
              } else {
                callback();
              }
            } },
          ],
      	},

        maxYear: new Date().getFullYear(),
        // 年
        yearList: [],
        // 月
        monthList: [
          {label: '1月', value: '01'},
          {label: '2月', value: '02'},
          {label: '3月', value: '03'},
          {label: '4月', value: '04'},
          {label: '5月', value: '05'},
          {label: '6月', value: '06'},
          {label: '7月', value: '07'},
          {label: '8月', value: '08'},
          {label: '9月', value: '09'},
          {label: '10月', value: '10'},
          {label: '11月', value: '11'},
          {label: '12月', value: '12'},
        ],
      },

      // 上传报告行，一级行
      reportRow: null,


      // 导入检查报告弹窗
      uploadRecord: {
        visible: false,
        tableData: [],
      }

		}
	},
	computed: {
		
	},
	mounted() {
    let yearList = [];
    for(let i = 1900; i <= new Date().getFullYear(); i++) {
      yearList.push({
        label: i+'年',
        value: i
      });
    }
    this.addPatientDialog.yearList = yearList;

		this.searchPage();
	},
	methods: {
    switchTime: Tools.switchTime,

		// 页面类表 -----------------------
		searchPage() {
			this.paging.current = 1;
			this.getPage();
		},
		getPage() {
			let params = {
				cardID: this.form.cardID,
				name: this.form.name,
				gender: this.form.gender,
        is_collect: this.form.is_collect,
				page: this.paging.current,
				pageSize: this.paging.pageSize
			}
			if(this.form.time?.length) {
				params.startDiagnosisTime = this.form.time[0]+' 00:00:00';
				params.endDiagnosisTime = this.form.time[1]+' 23:59:59';
			}
			this.table.loading = true;
			axios({
				method: 'get',
				url: BASE_API+'/listPatient/',
				params: params
			}).then(res => {
        if(!res.data.result) {
					return;
				}
        // 视屏列表
        this.videoList = res.data.video_list;

				this.paging.total = res.data.total;
				res = JSON.parse(res.data.data);
        console.log(res);
				this.table.data = res.map((item, index) => {
					let data = item.fields
					data.sort = (this.paging.current-1)*this.paging.pageSize+index+1;
					data.id = item.pk;
					data.gender_text = data.gender == 1 ? '男' : data.gender == 2 ? '女' : '';
					data.expanded = false;
          data.children = [];
          // 判断当前是否有视屏
          let hasVideo = false;
          for(let key in this.videoList[data.id]) {
            if(this.videoList[data.id][key]?.length) {
              hasVideo = true;
              break;
            }
          }
          data.hasVideo = hasVideo;
          return data;
				})
			}).finally(() => {
				this.table.loading = false;
			})
		},

    // 展开行
    expandChange(row, expanded) {
      // 判断是展开还是关闭
      if(expanded.includes(row)) { // 展开
        row.expanded = true;
        this.reloadDiagnosis(row);
      } else {
        row.expanded = false;
      }
    },

    // 更新诊疗信息
    reloadDiagnosis(row) {
      axios({
        method: 'get',
        url: BASE_API+'/listPatientDiagnosis/',
        params: {
          patientId: row.id
        }
      }).then(data => {
        if(!data.data.result) {
          return;
        }
        let reprot_list = data.data.reprot_list[row.id];
        let res = JSON.parse(data.data.data);
        row.children = res.map(item => {
          let data = item.fields;
          data.id = item.pk;
          data.diagnosisAge = Tools.getAge(row.birthday, data.diagnosisTime);
          // 判断当前就诊记录是否有视屏
          let hasVideo = false;
          if(this.videoList[row.id][data.id]?.length) {
            hasVideo = true;
          }
          data.hasVideo = hasVideo;
          // 查看报告
          data.report = reprot_list[data.id] || '';
          return data;
        })
      })
    },

    // 单击行
    rowClick(row) {
      this.$refs.list.toggleRowExpansion(row, !row.expanded);
    },

    handleSizeChange1(pageSize) {
    	this.paging.pageSize = pageSize;
    	this.getPage();
    },

    handleCurrentChange1(current) {
    	this.paging.current = current;
    	this.getPage();
    },

    // 
    showDialog(row) {
    	this.historyDialog.visible = true;
    	this.historyDialog.title = row.name+"-就诊记录";
    	axios({
				method: 'get',
				url: BASE_API+'/listPatientDiagnosis/',
				params: {
					patientId: row.id
				}
			}).then(res => {
				if(!res.data.result) {
					return;
				}
				res = JSON.parse(res.data.data);
				this.historyDialog.tableData = res.map(item => {
					let data = item.fields;
					data.id = item.pk;
					data.diagnosisTime = data.diagnosisTime ? Tools.switchTime(data.diagnosisTime, 'yyyy-MM-dd HH:mm:ss') : '';
					return data;
				})
			})
    },

    handleSizeChange2() {

    },

    handleCurrentChange2() {

    },

    // 显示影像记录
    showVideoRecord(id, name, detailId) {
    	let options = {
    		id: id,
    		name: name
    	}
    	if(detailId) {
    		options.detailId = detailId;
    	}
    	window.location.href = Tools.joinUrl('./videoRecord.html', options);
    },

    // 修改收藏
    changeCollect(row) {
      axios({
        method: 'post',
        url: BASE_API+'/updatePatientCollect/',
        data: {
          patientId: row.id,
          is_collect: row.is_collect
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
        },
      }).then(res => {})
    },

    // 显示报告
    showReport(report) {
      window.open(BASE_API+report);
    },

    // 显示上传报告
    clickUploadReport(row1, row2) {
      this.reportRow = row1;
      this.$refs.reportRef.dataset.id = row2.id;
      this.$refs.reportRef.click();
    },

    // 上传报告改变
    uploadReportFile(e) {
      let files = e.target.files;
      if(!files.length) {
        return;
      }
      
      let file = files[0];
      let filename = file.name;
      let arr = filename.split('.');
      let filetype = arr[arr.length - 1];
      if(['doc', 'docx'].indexOf(filetype) == -1) {
        this.$notify({
          duration: 1000,
          title: '提示',
          message: '请上传WORD报告',
          type: 'error'
        });
        return;
      }
      let formData = new FormData();
      formData.append('id', e.target.dataset.id);
      formData.append('file', file);

      const loading = this.$loading({
        lock: true,
        text: '报告上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      axios({
        method: 'post',
        url: BASE_API+'/uploadReportFile/',
        headers: {
          'accepts': 'application/json',
          'Content-Type':'multipart/form-data',
        },
        data: formData
      }).then(res => {
        if(res.data.result) {
          this.$notify({
            duration: 1000,
            type: 'success',
            title: '提示',
            message: '上传成功!'
          });
          this.reloadDiagnosis(this.reportRow);
        }
      }).finally(() => {
        e.target.value = '';
        loading.close();
      })
    },

    // 选择改变
    handleSelectionChange(val) {
      this.selectedRows = val;
    },

    // 导出检查结果
    async exportResult() {
      // 验证密码是否设置
      let resSetting = await axios({
        method: 'get',
        url: BASE_API+'/getSystemSettings/'
      })
      resSetting = JSON.parse(resSetting.data.data)[0].fields;
      if(!resSetting.password) {
        this.$message.error('请先在系统设置中设置导出密码');
        return;
      }


      let message = '请确认是否导出所有检查信息，如果要导出特定检查信息，请选择！';
      if(this.selectedRows.length) {
        message = '请确认是否导出选中检查信息';
      }
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        showCancelButton: false,
        type: 'warning',
        center: true
      }).then(() => {
        let params = {}
        if(this.selectedRows.length) {
          params.patientIds = this.selectedRows.map(item => item.id);
        }
        axios({
          method: 'post',
          url: BASE_API+'/exportDatas/',
          data: params,
          headers: {
            'accepts': 'application/json'
          },
        }).then(res => {
          let url = res.data.file;
          this.$confirm(`检查信息已导出到：${url}`, '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'success',
            center: true
          }).then(() => {}).catch(() => {});
        })
      }).catch(() => {});
    },

    // 显示新增 --------------------
    showAddPatient() {
      this.addPatientDialog.form.year = '';
      this.addPatientDialog.form.month = '';
      setTimeout(() => {
        if(this.$refs.addPatientDialogForm) {
          this.$refs.addPatientDialogForm.resetFields();
          this.$refs.addPatientDialogForm.clearValidate();
          this.addPatientDialog.showIdTip = false;
        }
        this.addPatientDialog.visible = true;
      }, 50);
    },

    // 提交信息
    addPatientSubmit() {
    	this.$refs.addPatientDialogForm.validate((valid) => {
    		if(!valid) {
    			return;
    		}
    		if(this.addPatientDialog.showIdTip) {
    			this.$notify({
            duration: 1000,
	          title: '提示',
	          message: 'ID不能重复',
	          type: 'error'
	        });
    			return;
    		}
    		let params = {
    			...this.addPatientDialog.form
    		}
        params.birthday = params.year + '-' + params.month + '-01 00:00:00';
    		axios({
    			method: 'post',
    			url: BASE_API+'/addPatient/',
    			headers: {
				    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
				  },
				  data: params
    		}).then(res => {
    			if(res.data.result) {
    				this.$notify({
              duration: 1000,
		          title: '提示',
		          message: '添加成功',
		          type: 'success'
		        });
		        this.addPatientDialog.visible = false;
		        this.searchPage();
    			}
    		})
    	})
    },

    // 验证CARID是否存在
    checkId() {
      if(!this.addPatientDialog.form.cardID.length) {
        this.addPatientDialog.showIdTip = false;
        return;
      }
    	axios({
				method: 'get',
				url: BASE_API+'/listPatient/',
				params: {
					cardID: this.addPatientDialog.form.cardID
				}
			}).then(res => {
				if(!res.data.result) {
					return;
				}
				res = JSON.parse(res.data.data);
				this.addPatientDialog.showIdTip = res.length ? true : false;
			})
    },

    searchById() {
    	this.addPatientDialog.visible = false;
    	// this.form.id = this.addPatientDialog.form.id;
    	this.searchPage();
    },

    // 改变年
    changeYear() {
      if(!(this.addPatientDialog.form.year >= 1 && this.addPatientDialog.form.year <= this.addPatientDialog.maxYear)) {
        this.$notify({
          duration: 1000,
          title: '提示',
          message: '请输入小于'+this.addPatientDialog.maxYear+'的年',
          type: 'error'
        });
        this.addPatientDialog.form.year = '';
      }
    },
    // 该变月
    changeMonth() {
      if(!(this.addPatientDialog.form.month >= 1 && this.addPatientDialog.form.month <= 12)) {
        this.$notify({
          duration: 1000,
          title: '提示',
          message: '请输入1至12的月',
          type: 'error'
        });
        this.addPatientDialog.form.month = '';
      }
    },

    showUploadHz() {
      this.$refs.hzRef.click();
    },

    // 上传患者
    uploadHzFile(e) {
      let files = e.target.files;
      if(!files.length) {
        return;
      }
      
      let file = files[0];
      let filename = file.name;
      let arr = filename.split('.');
      let filetype = arr[arr.length - 1];
      if(['xls', 'xlsx'].indexOf(filetype) == -1) {
        this.$notify({
          duration: 1000,
          title: '提示',
          message: '请上传Excel',
          type: 'error'
        });
        return;
      }
      let formData = new FormData();
      formData.append('file', file);

      const loading = this.$loading({
        lock: true,
        text: '报告上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      axios({
        method: 'post',
        url: BASE_API+'/uploadPatientFiles/',
        headers: {
          'accepts': 'application/json',
          'Content-Type':'multipart/form-data',
        },
        data: formData
      }).then(res => {
        if(res.data.result) {
          this.$confirm(`共上传患者信息${res.data.total}条，成功导入${res.data.success_num}条！`, '提示', {
            confirmButtonText: '确定',
            showCancelButton: false,
            type: 'warning',
            center: true
          }).then(() => {}).catch(() => {});
          this.searchPage();
        } else {
          this.$alert(res.data.msg, '导入错误', {
            type: 'error'
          });
        }
      }).finally(() => {
        e.target.value = '';
        loading.close();
      })
    },

    // -------导入检查信息-------------------
    showUploadResult() {
      axios({
        method: 'get',
        url: BASE_API+'/getImportFiles/'
      }).then(res => {
        this.uploadRecord.tableData = res.data.files;
        this.uploadRecord.visible = true;
      })
    },

    confirmUploadRecord(row) {
      this.$prompt(`请确认是否导入检查信息：${row.name}！`, `请输入文件密码`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password'
      }).then(({ value }) => {
        let formData = new FormData();
        formData.append('inputFile', row.path);
        formData.append('password', value);
        axios({
          method: 'post',
          url: BASE_API+'/importDatas/',
          headers: {
            'accepts': 'application/json',
            'Content-Type':'multipart/form-data',
          },
          data: formData
        }).then(res => {
          if(res.data.result) {
            this.$notify({
              duration: 1000,
              title: '提示',
              message: '导入成功',
              type: 'success'
            });
            this.searchPage();
          } else if (res.data.code == 101) {
            this.$message.error('导出密码错误');
          }
        })
      }).catch(() => {});
      return;

      // this.$confirm(`请确认是否导入检查信息：${row.name}！`, '提示', {
      //   confirmButtonText: '确定',
      //   showCancelButton: false,
      //   type: 'warning',
      //   center: true
      // }).then(() => {
        
      // }).catch(() => {});
    }

	}
})